﻿using DKPScoreWebApi.DTOs.Requests;
using DKPScoreWebApi.DTOs.Results;
using DKPScoreWebApi.Models;
using DKPScoreWebApi.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace DKPScoreWebApi.Controllers
{
    [ApiController]
    [Route("api/guilds/{guildId}/members")]
    public class MembersController : ControllerBase
    {
        private readonly IMemberService _memberService;
        private readonly IDkpService _dkpService;
        private readonly IGuildService _guildService;
        private readonly ILogger<MembersController> _logger;

        public MembersController(IMemberService memberService, IDkpService dkpService, IGuildService guildService, ILogger<MembersController> logger)
        {
            _memberService = memberService;
            _dkpService = dkpService;
            _guildService = guildService;
            _logger = logger;
        }

        [HttpGet]
        public async Task<ActionResult<ApiResult<List<GuildMember>>>> GetMembers(int userId, int guildId, [FromQuery] bool activeOnly = true)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                var members = await _memberService.GetGuildMembersAsync(guildId, activeOnly);
                return Ok(new ApiResult<List<GuildMember>> { Success = true, Data = members });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工会成员失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取成员列表失败" });
            }
        }

        [HttpPost]
        public async Task<ActionResult<ApiResult<GuildMember>>> AddMember(int userId, int guildId, [FromBody] AddMemberRequest request)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                var member = await _memberService.AddGuildMemberAsync(guildId, request);
                return Ok(new ApiResult<GuildMember> { Success = true, Data = member });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加工会成员失败");
                return BadRequest(new ApiResult { Success = false, Message = ex.Message });
            }
        }

        [HttpGet("{memberId}")]
        public async Task<ActionResult<ApiResult<object>>> GetMemberDetail(int userId, int guildId, int memberId)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                var member = await _memberService.GetMemberByIdAsync(memberId);
                if (member == null || member.GuildId != guildId)
                    return NotFound(new ApiResult { Success = false, Message = "成员不存在" });

                var records = await _dkpService.GetMemberRecordsAsync(guildId, memberId);
                var totalPoints = await _dkpService.GetGuildRankingAsync(guildId)
                    .ContinueWith(t => t.Result.FirstOrDefault(m => m.Id == memberId)?.TotalPoints ?? 0);

                return Ok(new ApiResult<object>
                {
                    Success = true,
                    Data = new
                    {
                        Member = member,
                        TotalPoints = totalPoints,
                        Records = records
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取成员详情失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取成员详情失败" });
            }
        }

        [HttpPut("{memberId}")]
        public async Task<ActionResult<ApiResult>> UpdateMember(int userId, int guildId, int memberId, [FromBody] AddMemberRequest request)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                var success = await _memberService.UpdateMemberAsync(memberId, request);
                if (!success)
                    return NotFound(new ApiResult { Success = false, Message = "成员不存在" });

                return Ok(new ApiResult { Success = true, Message = "更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新成员失败");
                return BadRequest(new ApiResult { Success = false, Message = "更新成员失败" });
            }
        }

        [HttpDelete("{memberId}")]
        public async Task<ActionResult<ApiResult>> RemoveMember(int userId, int guildId, int memberId)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                var success = await _memberService.RemoveGuildMemberAsync(guildId, memberId);
                if (!success)
                    return NotFound(new ApiResult { Success = false, Message = "成员不存在" });

                return Ok(new ApiResult { Success = true, Message = "移除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "移除成员失败");
                return BadRequest(new ApiResult { Success = false, Message = "移除成员失败" });
            }
        }

        [HttpPatch("{memberId}/restore")]
        public async Task<ActionResult<ApiResult>> RestoreMember(int userId, int guildId, int memberId)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                var success = await _memberService.RestoreGuildMemberAsync(guildId, memberId);
                if (!success)
                    return NotFound(new ApiResult { Success = false, Message = "成员不存在" });

                return Ok(new ApiResult { Success = true, Message = "恢复成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复成员失败");
                return BadRequest(new ApiResult { Success = false, Message = "恢复成员失败" });
            }
        }

        [HttpGet("search")]
        public async Task<ActionResult<ApiResult<List<GuildMember>>>> SearchMembers(int userId, int guildId, [FromQuery] string q)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                var members = await _memberService.SearchMembersAsync(guildId, q);
                return Ok(new ApiResult<List<GuildMember>> { Success = true, Data = members });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索成员失败");
                return BadRequest(new ApiResult { Success = false, Message = "搜索成员失败" });
            }
        }
    }
}
